package com.lanlian.uikit;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lanlian.utillib.DisplayUtil;
import com.lanlian.utillib.ViewFindUtils;

import java.util.ArrayList;

/**
 * 标题按钮上的弹窗
 */
public class TitlePopupWindow {

    private Activity activity;
    private WindowManager.LayoutParams params;
    private boolean isShow;
    private WindowManager windowManager;
    private ViewGroup rootView;
    //弹窗子类项选中时的监听
    private OnItemOnClickListener mItemOnClickListener;
    //定义列表对象
    private ListView mListView;
    //定义弹窗子类项列表
    private ArrayList<ActionItem> mActionItems = new ArrayList<>();

    private final int animDuration = 250;//动画执行时间
    private boolean isAniming;//动画是否在执行
    //判断是否需要添加或更新列表子类项
    private boolean mIsDirty;

    public TitlePopupWindow(Activity activity, int width, int height) {
        this.activity = activity;
        windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
    }

    public TitlePopupWindow(Context activity) {
        this.activity = (Activity) activity;
        windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
    }

    public TitlePopupWindow(Activity activity) {
        this.activity = activity;
        windowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
    }

    public void initLayout() {
        //这是根布局
        rootView = (ViewGroup) View.inflate(activity, R.layout.title_popup, null);
        mListView = (ListView) rootView.findViewById(R.id.linearLayout);

        mListView.setAdapter(new BaseAdapter() {
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if (convertView == null) {
                    convertView = LinearLayout.inflate(activity, R.layout.title_pop_item, null);
                }
                TextView textView = ViewFindUtils.hold(convertView, R.id.tv);
                ImageView image = ViewFindUtils.hold(convertView, R.id.image);
                ActionItem item = mActionItems.get(position);
                textView.setText(item.mTitle);
                if (item.color != 0) {
                    textView.setTextColor(activity.getResources().getColor(item.color));
                }
                image.setImageDrawable(item.mDrawable);

                return convertView;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public Object getItem(int position) {
                return mActionItems.get(position);
            }

            @Override
            public int getCount() {
                return mActionItems.size();
            }
        });

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
                dismissPopupWindow();
                if (mItemOnClickListener != null) {
                    mItemOnClickListener.onItemClick(mActionItems.get(index), index);
                }
            }
        });

        //这里给你根布局设置背景透明, 为的是让他看起来和activity的布局一样
        params = new WindowManager.LayoutParams();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        params.format = PixelFormat.RGBA_8888;//背景透明
        params.gravity = Gravity.LEFT | Gravity.TOP;

        //当点击根布局时, 隐藏
        rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissPopupWindow();
            }
        });

        rootView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //如果是显示状态那么隐藏视图
                if (keyCode == KeyEvent.KEYCODE_BACK && isShow) {
                    dismissPopupWindow();
                }
                return isShow;
            }
        });
    }

    /**
     * 弹出选项弹窗
     *
     * @param locationView 默认在该view的下方弹出, 和popupWindow类似
     */
    public void show(View locationView) {
        if (mIsDirty) {
            initLayout();
        }

        if (!isAniming) {
            isAniming = true;
            try {
                //这个步骤是得到该view相对于屏幕的坐标, 注意不是相对于父布局哦!
                int[] arr = new int[2];
                locationView.getLocationOnScreen(arr);
                mListView.measure(0, 0);
                Rect frame = new Rect();
                activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);//得到状态栏高度
                float x = DisplayUtil.getScreenWidth(activity) - DisplayUtil.dip2px(activity, 150) -
                        DisplayUtil.dip2px(activity, 10);
                float y = arr[1] - frame.top + locationView.getHeight() + DisplayUtil.dip2px(activity, 3);
                mListView.setX(x);
                mListView.setY(y);

//                setBlurBackground();

                windowManager.addView(rootView, params);

                //这一步就是有回弹效果的弹出动画, 我用属性动画写的, 很简单
                showAnim(mListView, 0, 1, animDuration, true);

                //视图被弹出来时得到焦点, 否则就捕获不到Touch事件
                rootView.setFocusable(true);
                rootView.setFocusableInTouchMode(true);
                rootView.requestFocus();
                rootView.requestFocusFromTouch();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 弹出选项弹窗
     */
    public void show() {
        if (mIsDirty) {
            initLayout();
        }

        if (!isAniming) {
            isAniming = true;
            try {
                //这个步骤是得到该view相对于屏幕的坐标, 注意不是相对于父布局哦!
                int[] arr = new int[2];
                mListView.measure(0, 0);
                Rect frame = new Rect();
                activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);//得到状态栏高度
                float x = DisplayUtil.getScreenWidth(activity) - DisplayUtil.dip2px(activity, 150) -
                        DisplayUtil.dip2px(activity, 10);
                float y = arr[1] - frame.top + DisplayUtil.dip2px(activity, 53);
                mListView.setX(x);
                mListView.setY(y);

//                setBlurBackground();

                windowManager.addView(rootView, params);

                //这一步就是有回弹效果的弹出动画, 我用属性动画写的, 很简单
                showAnim(mListView, 0, 1, animDuration, true);

                //视图被弹出来时得到焦点, 否则就捕获不到Touch事件
                rootView.setFocusable(true);
                rootView.setFocusableInTouchMode(true);
                rootView.requestFocus();
                rootView.requestFocusFromTouch();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setBlurBackground() {
        rootView.setAlpha(0);
        rootView.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        alphaAnim(rootView, 0, 1, animDuration);
    }

    public void dismissPopupWindow() {
        if (!isAniming) {
            isAniming = true;
            isShow = false;
            goneAnim(mListView, 0.95f, 1, animDuration / 3, true);
        }
    }

    public WindowManager.LayoutParams getLayoutParams() {
        return params;
    }

    public ListView getLayout() {
        return mListView;
    }

    /**
     * popupwindow是否是显示状态
     */
    public boolean isShow() {
        return isShow;
    }

    private void alphaAnim(final View view, int start, int end, int duration) {
        ValueAnimator va = ValueAnimator.ofFloat(start, end).setDuration(duration);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                view.setAlpha(value);
            }
        });
        va.start();
    }

    private void showAnim(final View view, float start, final float end, int duration, final boolean isWhile) {
        ValueAnimator va = ValueAnimator.ofFloat(start, end).setDuration(duration);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                view.setPivotX(view.getWidth());
                view.setPivotY(0);
                view.setScaleX(value);
                view.setScaleY(value);
            }
        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (isWhile) {
                    showAnim(view, end, 0.95f, animDuration / 3, false);
                } else {
                    isAniming = false;
                }
            }
        });
        va.start();
    }

    public void goneAnim(final View view, float start, final float end, int duration, final boolean isWhile) {
        ValueAnimator va = ValueAnimator.ofFloat(start, end).setDuration(duration);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                view.setPivotX(view.getWidth());
                view.setPivotY(0);
                view.setScaleX(value);
                view.setScaleY(value);
            }
        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (isWhile) {
                    alphaAnim(rootView, 1, 0, animDuration);
                    goneAnim(view, end, 0f, animDuration, false);
                } else {
                    try {
                        windowManager.removeViewImmediate(rootView);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    isAniming = false;
                }
            }
        });
        va.start();
    }

    /**
     * 添加子类项
     */
    public void addAction(ActionItem action) {
        if (action != null) {
            mActionItems.add(action);
            mIsDirty = true;
        }
    }

    /**
     * 清除子类项
     */
    public void cleanAction() {
        if (mActionItems.isEmpty()) {
            mActionItems.clear();
            mIsDirty = true;
        }
    }

    /**
     * 根据位置得到子类项
     */
    public ActionItem getAction(int position) {
        if (position < 0 || position > mActionItems.size())
            return null;
        return mActionItems.get(position);
    }

    /**
     * 设置监听事件
     */
    public void setItemOnClickListener(OnItemOnClickListener onItemOnClickListener) {
        this.mItemOnClickListener = onItemOnClickListener;
    }

    /**
     * 功能描述：弹窗子类项按钮监听事件
     */
    public interface OnItemOnClickListener {
        void onItemClick(ActionItem item, int position);
    }

}